from PyQt6 import QtWidgets
from PyQt6.QtWidgets import QApplication, QTableWidget, QVBoxLayout, QPushButton, QWidget, QRadioButton, QButtonGroup


class CustomRadioButton(QRadioButton):
    def mousePressEvent(self, event):
        # 如果当前按钮已被选中，则取消选中
        if self.isChecked():
            self.setChecked(False)
        else:
            # 如果按钮未被选中，先取消所有按钮的选中状态，然后设置当前按钮为选中
            button_group = self.group()
            if button_group:
                for button in button_group.buttons():
                    button.setChecked(False)
            self.setChecked(True)
        # 防止事件传播，默认处理
        event.accept()


class TestWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout()

        # Create QTableWidget and add it to layout
        self.tableWidget = QTableWidget(3, 1)
        layout.addWidget(self.tableWidget)

        # Create a QButtonGroup to manage radio buttons
        self.radio_button_group = QButtonGroup()

        # Add CustomRadioButton to each row of the table and add them to the button group
        for row in range(3):
            radio_button = CustomRadioButton(f"Radio {row}")
            self.tableWidget.setCellWidget(row, 0, radio_button)
            radio_button.setChecked(False)  # Default to not checked
            self.radio_button_group.addButton(radio_button)

        # Create a button to clear radio buttons
        self.clear_button = QPushButton("Clear Selection")
        self.clear_button.clicked.connect(self.clear_all_radio_buttons)
        layout.addWidget(self.clear_button)

        self.setLayout(layout)
        self.setWindowTitle('Test Window')
        self.show()

    def clear_all_radio_buttons(self):
        # Clear all QRadioButton selections in the group
        for button in self.radio_button_group.buttons():
            button.setChecked(False)
        QApplication.processEvents()  # Process events to ensure UI updates


app = QApplication([])
window = TestWindow()
app.exec()
